/*
 * cafe-layermange.js
 * @Author :      SHOUHUAJIE
 * @CreateDate :  2019年2月19日
 * 图层管理
 */
;define(function() {
	// 创建主界面
	function bulidHtml(cfg) {
		var $warp = $('<div>').addClass("cafe-layer");

		var $header = $(`
			<div class="cafe-layer-header">
				<div class="cafe-layer-title">产品图层</div>
			</div>
		`);
		var $body = $('<div>').addClass('cafe-layer-body');

		var $commonOperate = $(`
			<div class="cafe-layer-common-operate">
				<span class='layer-sync disabled' title='同步'></span>
				<span class='layer-mutex' title='互斥'></span>
				<span class='layer-eye' title='全部显隐'></span>
				<span class='layer-close' title='全部关闭'></span>
			</div>
		`);

		var $item = bulidLayer(cfg);
		$body.append($item);

		$warp.append($header).append($commonOperate).append($body);
		return $warp;
	}
	function bulidLayer(cfg) {
		var $item = $('<div>').addClass('cafe-layer-item');
		$item.data('proInfo', cfg.proInfo);
		var $layerName = $('<div>').addClass('cafe-layer-name');
		var layerName = cfg.proInfo.name + '_' + new Date(cfg.proInfo.time).format('yyyy-MM-dd/hh:mm');
		$layerName.html(layerName).attr('title', layerName);

		var $layerOperate = $(`
			<div class="cafe-layer-operate">
				<span class='layer-eye' title='图层显隐'></span>
				<span class='time-align' title='时间对齐'></span>
				<span class='time-prev' title='时间向前'></span>
				<span class='time-next' title='时间向后'></span>
				<span class='more-info' title='站点详情'></span>
				<span class='layer-change'></span>
				<span class='layer-close' title='关闭图层'></span>
			</div>
		`);
		if (cfg.proInfo.isGrid || !cfg.proInfo.isSK) {
			$layerOperate.find('.more-info').hide();
		}
		$item.append($layerName).append($layerOperate);

		return $item;
	}
	// 获取时间
	function getDate(date,cfg){
		var getVal = function(val){
			return Math.floor(val/cfg.timeInterval)*cfg.timeInterval;
		};
		if(cfg.dateFmt.endsWith("hh")){
			var hour = date.getHours();
			if(cfg.customHm.length > 0){
				if(hour < cfg.customHm[0]){
					date.setDate(date.getDate()-1);
					hour = cfg.customHm[cfg.customHm.length-1];
				}else{
					for(var i = cfg.customHm.length-1; i>=0 ; i--){
						if(hour >= cfg.customHm[i]){
							hour = cfg.customHm[i];
							break;
						}
					}
				}
			}else{
				hour = getVal(hour);
			}
			date.setHours(hour);
		}else{
			var min = date.getMinutes();
			if(cfg.customHm && cfg.customHm.length > 0){
				cfg.customHm = cfg.customHm.sort();
				if(min < cfg.customHm[0]){
					date.setHours(date.getHours()-1);
					min = cfg.customHm[cfg.customHm.length-1];
				}else{
					for(var i = cfg.customHm.length-1; i>=0 ; i--){
						if(min >= cfg.customHm[i]){
							min = cfg.customHm[i];
							break;
						}
					}
				}	
			}else{
				if(cfg.dateFmt.endsWith("yyyy")){
                    date.setFullYear(date.getFullYear(),0,1);
                    date.setHours(0,0);
				}else if(cfg.dateFmt.endsWith("MM")){
                    date.setMonth(date.getMonth(),1);
                    date.setHours(0,0);
				}else{
                    date.setMinutes(getVal(min));
				}
			}
		}
		return date.toString("yyyy-MM-dd hh:mm");
	}
	/**
	 * 绑定事件
	 */
	function _eves($drop, cfg) {
		$drop.off().on("click", ".cafe-layer-item", function(e) { // 点击事件
			e.stopPropagation();
			if ($(this).hasClass('active')) {
				return;
			} else {
				$(this).addClass('active').siblings().removeClass('active');
			}
			if($.isFunction(cfg.call)){
				var proInfo = $(this).data('proInfo');
				cfg.call(proInfo);
			}
		}).on("click", ".cafe-layer-item .layer-eye", function(e) { // 隐藏图层
			e.stopPropagation();
			var isActive = $(this).hasClass('disabled');
			if (isActive) {
				$(this).removeClass('disabled');
			} else {
				$(this).addClass('disabled');
			}
			var proInfo = $(this).parent().parent().data('proInfo');
			if (proInfo.isGrid) { // 格点
				var layerIds = [], layerID = proInfo.ele.ele_id;
				if (!layerID) return;
				if( proInfo.ele.height){
					layerID = layerID+proInfo.ele.height;
				}
				GLMap.layerIds.forEach(function(layerId){
					if (layerId.indexOf('-layer') != -1 && layerId.indexOf(layerID) != -1) {
						layerIds.push(layerId);
					}
				})
				GIS.LayerControll.showControll(cfg.mapId, layerIds, isActive);
			} else {
				var statArr = CafeJS.tqfx.toolsBar.getStationType().split(',');
				GIS.Station.eleShowControl(cfg.mapId, statArr, [proInfo.ele.type], isActive ? "show" : "hide");
				if (proInfo.ele.type == 'WIND') {
					CafeJS.tqfx.statSignControl(CafeJS.tqfx.toolsBar.isToolActive('windbar'), "", isActive);
					CafeJS.tqfx.statSignControl(CafeJS.tqfx.toolsBar.isToolActive('windspeed'), "TxtBg", isActive);
				}
			}
		}).on("click", ".cafe-layer-operate span", function(e) {
			e.stopPropagation();
			if (!$(this).hasClass('layer-eye'))
			$(this).parent().parent().trigger('click');
		}).on("click", ".cafe-layer-operate .time-align", function(e) { // 时间对齐
			e.stopPropagation();
			var selectProInfo = $(this).parent().parent().data('proInfo');
			var time = selectProInfo.time;
			$drop.find('.cafe-layer-item').each(function(){
				var proInfo = $(this).data('proInfo');
				if ($(this).hasClass('active') || selectProInfo.bussitype != proInfo.bussitype) return;
				$(this).find('span.layer-eye.disabled').removeClass('disabled');
				var dateOpt = CafeJS[proInfo.bussitype].playList.config.dateOpt;
				var newTime = getDate(new Date(time), dateOpt);
				proInfo.time = new Date(newTime).format(dateOpt.dateFmt.endsWith("hh") ? dateOpt.dateFmt + ':00' : dateOpt.dateFmt);
			    CafeJS[proInfo.bussitype].playList.config.call(proInfo); // 调用不同图层产品的请求
			})
		}).on("click", ".cafe-layer-operate .more-info", function(e) { // 详情
			e.stopPropagation();
			var proInfo = $(this).parent().parent().data('proInfo');
			if (!proInfo.isGrid && proInfo.isSK) {
				cfg.more(proInfo);
			}
		}).on("click", ".cafe-layer-operate .time-prev", function(e) { // 时间上翻
			e.stopPropagation();
			$("#a-m-timeline .cafe-tl-left-icon").trigger('click');
			if($(".cafe-layer-common-operate .layer-sync").hasClass("disabled"))
				return;
			$(this).parent().find(".time-align").trigger('click');
		}).on("click", ".cafe-layer-operate .time-next", function(e) { // 时间下翻
			e.stopPropagation();
			$("#a-m-timeline .cafe-tl-right-icon").trigger('click');
			if($(".cafe-layer-common-operate .layer-sync").hasClass("disabled"))
				return;
			$(this).parent().find(".time-align").trigger('click');
		}).on("click", ".cafe-layer-operate .layer-close", function(e) {
			e.stopPropagation();
			var proInfo = $(this).parent().parent().data('proInfo');
			CafeJS.layerManage.delLayer(proInfo);
		}).on("click", ".cafe-layer-common-operate .layer-eye", function(e) { // 隐藏所有图层
			e.stopPropagation();
			var isDisabled = $(this).hasClass('disabled');
			if (isDisabled) {
				$(this).removeClass('disabled');
			} else {
				$(this).addClass('disabled');
			}
			$drop.find('.cafe-layer-item').each(function(i, layer) {
				if (isDisabled) {
					if ($(layer).find('.layer-eye').hasClass('disabled')) {
						$(layer).find('.layer-eye').click();
					}
				} else {
					if (!$(layer).find('.layer-eye').hasClass('disabled')) {
						$(layer).find('.layer-eye').click();
					}
				}
			})
		}).on("click", ".cafe-layer-common-operate .layer-close", function(e) { // 图层移除
			e.stopPropagation();
			$drop.find('.cafe-layer-item').each(function(i, layer) {
				$(layer).find('.layer-close').click();
			})
		}).on("mousedown", ".cafe-layer-header", function(event){ // 拖动图层管理
			$(this).css({"cursor": "all-scroll"}); //点击鼠标切换图形
			event.stopPropagation();
			var isMove = true;
			var _this = $(".c-b-layermanage");

			var m_x = Number(_this.css("left").split("px")[0]);//点击窗体时，left
			var m_y = Number(_this.css("top").split("px")[0]);//点击窗体时，top
			var abs_x = event.pageX;		//点击窗体时，左边距
			var abs_y = event.pageY;		//点击窗体时，上边距
			//单击住头部可进行拖拽，计算移动大小，以及移动范围限制
			$(document).unbind('mousemove').bind('mousemove',function(event){
				if(isMove) {
					//event.pageX,移动后的左边距;event.pageY,移动后的上边距
					var ebs_x = m_x-(abs_x-event.pageX); //移动后的left
					var ebs_y = m_y+(event.pageY - abs_y);//移动后的top

					var body_w = $('.cafe-busis-container').width();
					var body_h = $('.cafe-busis-container').height();

					var div_w = _this.width();
					var div_h = _this.find(".c-b-layermanage").outerHeight();
					//不可超出左右边框
					if(ebs_x <= (0-div_w+75)) {
						ebs_x = 0-div_w+75;
					} else if (ebs_x > body_w - 75) {
						ebs_x = body_w - 75;
					}
					//不可超出上下边框
					if(ebs_y <= (0-div_h+75)) {
						ebs_y = 0-div_h+75;
					} else if (ebs_y > body_h - 75) {	//减去上下的蓝边高
						ebs_y = body_h - 75;
					}
					//重新设定弹出框的左边距，上边距
					_this.css({'left':ebs_x,'top':ebs_y,'bottom':'unset','right':'unset'});
				}
			}).mouseup(function(){
				isMove = false
				$(document).unbind('mousemove');
			});//鼠标移除事件；单击事件结束事件。
		}).on("click",".cafe-layer-common-operate .layer-mutex",function(e){
			e.stopPropagation();
			var isDisabled = $(this).hasClass('disabled');
			if (isDisabled) {
				$(this).removeClass('disabled');
				$(".cafe-layer-body").find(".cafe-layer-item").each(function(){
					var eleInfo = $(this).data('proInfo');
					var currentPageIsSK = $(".cafe-busis-toolsbar-left #zhsk").hasClass("active");
					if(currentPageIsSK){
						if(!eleInfo.isSK){
							$(this).find('.layer-close').click();
						}
					}else{
						if(eleInfo.isSK){
							$(this).find('.layer-close').click();
						}
					}
				})
			} else {
				$(this).addClass('disabled');
			}
		}).on("click",".cafe-layer-common-operate .layer-sync",function(e){
			e.stopPropagation();
			$(this).toggleClass('disabled');
			
		})
	}

	var CFLayerManage = function(settings) {
		var options = {
			appendTo : null,// 控件所在容器
			mapId : null,// map的ID
			proInfo: null, //产品信息
			call : null,// 图层点击事件
			more: null, // 自动站列表详情
			close : null // 关闭图层事件
		};
		this.config = $.extend({}, options, settings);
		this.init();
	}

	CFLayerManage.prototype = {
		init : function() {
			this.$drop = bulidHtml(this.config);
			if(this.config.appendTo){
				var $container = $(this.config.appendTo);
				$container.empty().show().append(this.$drop);
			}

			_eves(this.$drop,this.config);

			this.$drop.find('.cafe-layer-body').children().first().trigger('click');
		},
		addLayer: function(proInfo) {
			var $container = $(this.config.appendTo);
			// 如果是实况，删除同一类型的图层
			if (proInfo.isSK) {
				$container.find('.cafe-layer-item').each(function(i, item){
					if ($(item).data('proInfo').ele.type == proInfo.ele.type
					    && $(item).data('proInfo').isGrid === proInfo.isGrid) {
						$(item).remove();
						return false;
					}
				})
			}
			this.config.proInfo = proInfo;
			var $item = bulidLayer(this.config);
			$container.find('.cafe-layer-body').prepend($item);
			$container.find('.cafe-layer-body').children().first().trigger('click');
		},
		delLayer: function(proInfo) {
			var that = this;
			var $container = $(this.config.appendTo);
			$container.find('.cafe-layer-item').each(function(i, item){
				var temp = $(item).data('proInfo');
				if (temp.name == proInfo.name) {
					$(item).remove();
					if($.isFunction(that.config.close)){
						that.config.close(temp);
					}
					return false;
				}
			})
			$container.find('.cafe-layer-item').first().trigger('click');
		},
		removeLayer: function(proInfo) {
			var that = this;
			var $container = $(this.config.appendTo);
			$container.find('.cafe-layer-item').each(function(i, item){
				var temp = $(item).data('proInfo');
				if (temp.name == proInfo.name) {
					$(item).remove();
					return false;
				}
			})
			$container.find('.cafe-layer-item').first().trigger('click');
		},
		updateLayer: function(proInfo) {
			var $container = $(this.config.appendTo);
			$container.find('.cafe-layer-item').each(function(i, item){
				var temp = $(item).data('proInfo');
				if (temp.name == proInfo.name) {
					$(item).data('proInfo', proInfo);
					var oldDate = new Date(proInfo.time).format('yyyy-MM-dd hh:mm');
					var layerName = proInfo.name + '_' + new Date(proInfo.time).format('yyyy-MM-dd/hh:mm');

					if (!proInfo.isSK && proInfo.forecastTime) {
						layerName = proInfo.name + '_' + new Date(proInfo.time).format('MM-dd hh:mm') + '/' + new Date(proInfo.forecastTime).format('MM-dd hh:mm');
						oldDate = new Date(proInfo.forecastTime).format('yyyy-MM-dd hh:mm');
					}
					$(item).find('.cafe-layer-name').html(layerName).attr('title', layerName);
					$(item).attr("title",oldDate);
					var index = $(".cafe-tl-content .cafe-tl-item.active").index();
					$(item).attr("name",index);
					return false;
				}
			})
		},
		updateLayerTime: function(time, bussitype, forecastTime, id) {
			var $container = $(this.config.appendTo);
			$container.find('.cafe-layer-item').each(function(){
				var proInfo = $(this).data('proInfo');
				if (proInfo.bussitype == bussitype) {
					if (id && proInfo.ele.ele_id != id) return;
					proInfo.time = time;
					var layerName = proInfo.name + '_' + new Date(time).format('yyyy-MM-dd/hh:mm');
					if (forecastTime) {
						layerName = proInfo.name + '_' + new Date(time).format('MM-dd hh:mm') + '/' + new Date(forecastTime).format('MM-dd hh:mm');
					}
					$(this).find('.cafe-layer-name').html(layerName).attr('title', layerName);;
				}
			})
			var activeLayer = $container.find('.cafe-layer-item.active');
			activeLayer.removeClass('active').trigger('click');
        },
        getEleType: function() {
            var statType = [];
            var $container = $(this.config.appendTo);
			$container.find('.cafe-layer-item').each(function(){
                var proInfo = $(this).data('proInfo');
                if (proInfo.bussitype == 'autostat') {
                    if (!$(this).find('.layer-eye').hasClass('disabled')) {
                        statType.push(proInfo.ele.type);
                    }
                }
            })
           return statType;
        },
		show : function() {
			this.$drop.parent().show();
		},
		hide : function() {
			this.$drop.parent().hide();
			if ($.isFunction(this.config.close)) {
				this.config.close();
			}
		},
		removeLegent: function(id,bussitype){
			var $container = $(this.config.appendTo);
			$container.find('.cafe-layer-item').each(function(){
				var proInfo = $(this).data('proInfo');
				if (proInfo.bussitype == bussitype) {
					if (id && proInfo.ele.ele_id != id) return;
					$(this).find(".legentpicker").remove();
				}
			})
		},
		remove : function() {
			this.$drop.empty();
		}
	};

	CafeJS.LayerManage = function(settings) {
		var drop = new CFLayerManage(settings);
		return drop;
	}
});
